package es.udc.emarketapp.emarket.model.purchase.purchaseFacade.actions;

import es.udc.emarketapp.emarket.model.purchase.dao.SQLPurchaseDAO;
import es.udc.emarketapp.emarket.model.purchase.dao.SQLPurchaseDAOFactory;
import es.udc.emarketapp.emarket.model.purchase.purchaseFacade.vo.PurchaseChunkVO;
import es.udc.emarketapp.emarket.model.purchase.vo.PurchaseVO;

import java.sql.Connection;
import java.util.List;

import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.sql.NonTransactionalPlainAction;

public class FindPurchasesByClientAction implements NonTransactionalPlainAction {

	private String idClient;
	private int startIndex;
	private int count;

	public FindPurchasesByClientAction(String idClient, int startIndex, int count) {

		this.idClient = idClient;
		this.startIndex = startIndex;
		this.count = count;
	}

	/**
	 * 
	 * @return An instance of <code>PurchaseChunkVO</code> objects.
	 */
	public Object execute(Connection connection) throws InternalErrorException {

		/*
		 * Find count+1 purchases to determine if there exist more products
		 * above the specified range.
		 */
		SQLPurchaseDAO purchaseDAO = SQLPurchaseDAOFactory.getDAO();
		List<PurchaseVO> purchaseVOs = purchaseDAO.findByClient(connection,
				idClient, startIndex, count + 1);
		boolean existMorePurchases = purchaseVOs.size() == (count + 1);

		/*
		 * Remove the last account from the returned list if there exist more
		 * accounts above the specified range.
		 */
		if (existMorePurchases) {
			purchaseVOs.remove(purchaseVOs.size() - 1);
		}

		return new PurchaseChunkVO(purchaseVOs, existMorePurchases);

	}

}